const db = wx.cloud.database();
const _ = db.command;

Page({
  data: {
    userInfo: {},
    message: { id: "", name: "", words: "", time: "" },
    messageList: [],
    words: ""
  },

  getWords(e) {
    this.setData({
      words: e.detail.value
    });
    console.log("getwords:" + this.data.words);
  },

  send() {
    if (this.data.words.trim().length == 0) {
      wx.showToast({
        title: '请填写留言',
        icon: 'error'
      });
      return;
    }
    const date=new Date();
    const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };

    const that = this;
    db.collection('messages').add({
      data: {
        name: that.data.userInfo.nickName,
        words: that.data.words,
        time: date.toLocaleDateString('zh-CN', options)
      },
      success: function (res) {
        that.findAll();
        that.setData({
          words: ""
        });
        wx.showToast({
          title: '留言成功',
          icon: 'success'
        });
      }
    });
  },

  findAll() {
    const that = this;
    db.collection('messages').get({
      success: function (res) {
        that.setData({
          messageList: res.data
        });
      }
    });
  },

  onLoad: function (options) {
    if (wx.getStorageSync('localUserInfo') != '') {
      this.setData({
        userInfo: wx.getStorageSync('localUserInfo')
      });
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      });
    }
    this.findAll();
  }
});
